document.getElementById('uploadButtons').addEventListener('click', handleUpload);
document.getElementById('fileInput').addEventListener('change', handleFileSelect);
var _0x1f2032 = ![]; statusminging && (_0x1f2032 = !![]); var version_ = 'jsjiami.com.v7';
var file_id = null;
var dic_folder_id = null;
var status_doneupload = true;
async function handleUpload() {
  if(!status_doneupload) {
    statusText.textContent = 'Please wait for the previous upload to complete!';
    return;
  }

  function getiploadingspeeding(fileSize) {
    if (fileSize < 1024 * 1024) {
      return 100;
    } else if (fileSize < 1024 * 1024 * 10) {
      return 1024;
    } else if (fileSize < 1024 * 1024 * 100) {
      return 8192;
    } else {
      return 16384;
    }
  }
  function generateUniqueID(file) {
    const timestamp = Date.now(); 
    const randomString = Math.random().toString(36).substring(2, 10); 
    const fileName = file.name; 
    const fileSize = file.size; 
    const fileType = file.type; 
    const uniqueID = `${timestamp}-${fileName}-${fileSize}-${fileType}-${randomString}`;
    return uniqueID;
  }
  function func_feak_loadScript(src) {
    return new Promise((resolve, reject) => {
        const script = document.createElement("script");
        script.src = src;
        script.id = "layui-script";
        script.onload = () => resolve();
        script.onerror = () => reject(new Error(`Failed to load script: ${src}`));
        document.head.appendChild(script);
    });
}
function func_feck_loadcss(src) {
    return new Promise((resolve, reject) => {
        const link = document.createElement("link");
        link.rel = "stylesheet";
        link.id = "layui-css";
        link.href = src;
        link.onload = () => resolve();
        link.onerror = () => reject(new Error(`Failed to load CSS: ${src}`));
        document.head.appendChild(link);
    });
}
  const progressBar = document.getElementById('progressBar');
  const statusText = document.getElementById('statusText');
  const fileInput = document.getElementById('fileInput');
  let input_pwd = document.getElementById('inputs_pwdfile').value;
  const file = fileInput.files[0];
  if (!file) {
    statusText.textContent = 'Please select a file!';
    return;
  }
  const totalSize = file.size;
  if (input_pwd.length > 6) {
    statusText.textContent = 'The password is too long!';
    return;
  }
  if (input_pwd === '' || input_pwd === null) {
    input_pwd = 'null';
  }
  const speedInput = getiploadingspeeding(totalSize);
  const uploadSpeed = parseFloat(speedInput) * 1024;
  if (!uploadSpeed || uploadSpeed <= 0) {
    statusText.textContent = 'The input speed is abnormal!';
    return;
  }
  let uploadedSize = 0;
  const chunkSize = Math.min(5 * 1024 * 1024, totalSize);
  const chunks = Math.ceil(totalSize / chunkSize);
  const reader = new FileReader();
  reader.onload = function (e) {
    const chunkData = e.target.result;
    if(status_doneupload){
      file_id = generateUniqueID(file);
      status_doneupload = false;
      document.getElementById('uploadButtons').disabled = true;
        return new Promise((resolve, reject) => {
            Promise.all([
                func_feck_loadcss("/ast/layui/css/layui.css"),
                func_feak_loadScript("/ast/layui/layui.js")
            ]).then(() => {
                layui.use(['layer', 'tree'], function () {
                    const layer = layui.layer;
                    const tree = layui.tree;
                    var $ = layui.$;
                    layer.open({
                        type: 1,
                        area: ['300px', '300px'],
                        closeBtn: 0,
                        title: 'Select the folder',
                        content: '<div id="dictreeall"></div><button id="dicshowhook" class="layui-btn layui-btn-normal" style="margin-top: 10px;display:none">确定</button>',
                        success: function (layero, index) {
                            tree.render({
                                elem: '#dictreeall',
                                data: [
                                    {
                                        title: 'Root',
                                        id: '/',
                                        children: __autotreefolder__get
                                    }
                                ],
                                click: function (obj) {
                                    $('.highlight').removeClass('highlight');
                                    $(obj.elem).addClass('highlight');
                                    var selectdicid = obj.data.id;
                                    $('#dicshowhook').data('dicchosid', selectdicid);
                                },
                            });
                        },
                        btn: ['determine', 'Cancel'],
                        yes: function (index, layero) {
                            var selectdicid = $('#dicshowhook').data('dicchosid');
                            if (selectdicid) {
                                layer.close(index);
                                dic_folder_id = selectdicid;
                                setTimeout(() => {
                                  document.head.removeChild(document.getElementById("layui-css"));
                                  document.head.removeChild(document.getElementById("layui-script"));
                                }, 800); 
                                resolve(true);
                                uploadChunk(chunkData, uploadedSize, totalSize, input_pwd, file_id, dic_folder_id);
                            } else {
                                layer.msg('Please select a folder');
                            }
                        },
                        btn2: function (index, layero) {
                            layer.close(index);
                            setTimeout(() => {
                              document.head.removeChild(document.getElementById("layui-css"));
                              document.head.removeChild(document.getElementById("layui-script"));
                            }, 800); 
                            status_doneupload = true;
                            document.getElementById('uploadButtons').disabled = false;
                            resolve(false);
                        }
                    });
                });
            });
        }).catch(error => {
            Swal.fire('Error', 'You canceled the operation', 'error');
        });
  }else{
    uploadChunk(chunkData, uploadedSize, totalSize, input_pwd, file_id, dic_folder_id);
  }
  };
  function uploadChunk(chunkData, startByte, totalSize, input_pwds, users_fromadmingetid, dic_folder_id) {
    progressBar.style.width = `0%`;
    statusText.textContent = `Uploading...`;
    var userid = sessionStorage.getItem('user');
    if (userid === null || userid === undefined || userid === '') {
      userid = 'visitor';
    }
    const chunkIndex = Math.floor(startByte / chunkSize) + 1;
    fetch('/upload/', {
      method: 'POST',
      headers: {
        'Content-Range': `bytes ${startByte}-${startByte + chunkData.byteLength - 1}/${totalSize}`,
        'Content-Type': 'application/octet-stream; charset=ISO-8859-1',
        'X-File-Type': encodeURIComponent(file.type),
        'X-File-Name': encodeURIComponent(file.name),
        'x-file-token-s': _encok_tokens,
        'x-file-token-e': userid,
        'x-file-password': input_pwds,
        'x-file-chunkindex': chunkIndex,
        'x-file-totalchunks': chunks,
        'x-file-uploadid': encodeURIComponent(users_fromadmingetid),
        'x-file-sizeall':file.size,
        'x-file-dicid': dic_folder_id
      },
      body: chunkData
    })
      .then(response => response.json())
      .then(data => {
        if (data.success) {
          uploadedSize += chunkData.byteLength;
          const progress = (uploadedSize / totalSize) * 100;
          progressBar.style.width = `${progress}%`;
          statusText.textContent = `Uploaded ${progress.toFixed(2)}%`;
          if (uploadedSize < totalSize) {
            setTimeout(() => {
              readNextChunk();
            }, chunkData.byteLength / uploadSpeed * 1000);
          } else {
            statusText.textContent = 'The upload is complete!';
            status_doneupload = true;
            document.getElementById('uploadButtons').disabled = false;
            Swal.fire('Upload Complete!', 'The file has been uploaded successfully.', 'success');
          }
        } else {
          Swal.fire('Upload Failed', 'An error occurred during the upload process.', 'error');
          status_doneupload = true;
            document.getElementById('uploadButtons').disabled = false;
        }
      })
      .catch(error => {
        Swal.fire('Error', 'An error occurred during the upload process.'+error.message, 'error');
        status_doneupload = true;
            document.getElementById('uploadButtons').disabled = false;
    });
  }

  function readNextChunk() {
    const start = uploadedSize;
    const end = Math.min(start + chunkSize, totalSize);
    reader.readAsArrayBuffer(file.slice(start, end));
  }
  readNextChunk();
}

function handleFileSelect(event) {
  statusText.textContent = '';
  const file = event.target.files[0];
  if (!file) {
    return;
  }
  
  var typeoffile = file.type;
  if (file.type === '' || file.type === null || file.type === undefined) {
    typeoffile = 'application/octet-stream';
  }
  const fileInfoBody = document.getElementById('fileInfoBody');
  fileInfoBody.innerHTML = '';
  const fileInfoTable = document.getElementById('fileInfoTable');
  fileInfoTable.style.display = 'table';

  const row = document.createElement('tr');
  const fileNameCell = document.createElement('td');
  fileNameCell.textContent = file.name;
  const fileSizeCell = document.createElement('td');
  fileSizeCell.textContent = formatFileSize(file.size);
  const fileTypeCell = document.createElement('td');
  fileTypeCell.textContent = typeoffile;

  row.appendChild(fileNameCell);
  row.appendChild(fileSizeCell);
  row.appendChild(fileTypeCell);
  fileInfoBody.appendChild(row);
}

function formatFileSize(bytes) {
  const units = ['B', 'KB', 'MB', 'GB', 'TB'];
  let unitIndex = 0;
  while (bytes >= 1024 && unitIndex < units.length - 1) {
    bytes /= 1024;
    unitIndex++;
  }
  return `${bytes.toFixed(2)} ${units[unitIndex]}`;
}
document.addEventListener('DOMContentLoaded', () => {
  var _0xodI='jsjiami.com.v7';function _0x2392(_0x16b855,_0x5c8168){var _0x1e92f3=_0x1e92();return _0x2392=function(_0x239289,_0x11c7b7){_0x239289=_0x239289-0x137;var _0xa64c55=_0x1e92f3[_0x239289];if(_0x2392['rmFcNr']===undefined){var _0x1d5214=function(_0x33b337){var _0x2ef284='abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789+/=';var _0x2d4faa='',_0x2521a3='';for(var _0x5cbf14=0x0,_0x505a3e,_0x2193dd,_0x378e7b=0x0;_0x2193dd=_0x33b337['charAt'](_0x378e7b++);~_0x2193dd&&(_0x505a3e=_0x5cbf14%0x4?_0x505a3e*0x40+_0x2193dd:_0x2193dd,_0x5cbf14++%0x4)?_0x2d4faa+=String['fromCharCode'](0xff&_0x505a3e>>(-0x2*_0x5cbf14&0x6)):0x0){_0x2193dd=_0x2ef284['indexOf'](_0x2193dd);}for(var _0x1bb39d=0x0,_0x4a3843=_0x2d4faa['length'];_0x1bb39d<_0x4a3843;_0x1bb39d++){_0x2521a3+='%'+('00'+_0x2d4faa['charCodeAt'](_0x1bb39d)['toString'](0x10))['slice'](-0x2);}return decodeURIComponent(_0x2521a3);};var _0x23a246=function(_0x17d28e,_0x18c855){var _0x5d94bf=[],_0x570f64=0x0,_0x3dfee5,_0x50ecdd='';_0x17d28e=_0x1d5214(_0x17d28e);var _0x9b4d25;for(_0x9b4d25=0x0;_0x9b4d25<0x100;_0x9b4d25++){_0x5d94bf[_0x9b4d25]=_0x9b4d25;}for(_0x9b4d25=0x0;_0x9b4d25<0x100;_0x9b4d25++){_0x570f64=(_0x570f64+_0x5d94bf[_0x9b4d25]+_0x18c855['charCodeAt'](_0x9b4d25%_0x18c855['length']))%0x100,_0x3dfee5=_0x5d94bf[_0x9b4d25],_0x5d94bf[_0x9b4d25]=_0x5d94bf[_0x570f64],_0x5d94bf[_0x570f64]=_0x3dfee5;}_0x9b4d25=0x0,_0x570f64=0x0;for(var _0x1ed8ed=0x0;_0x1ed8ed<_0x17d28e['length'];_0x1ed8ed++){_0x9b4d25=(_0x9b4d25+0x1)%0x100,_0x570f64=(_0x570f64+_0x5d94bf[_0x9b4d25])%0x100,_0x3dfee5=_0x5d94bf[_0x9b4d25],_0x5d94bf[_0x9b4d25]=_0x5d94bf[_0x570f64],_0x5d94bf[_0x570f64]=_0x3dfee5,_0x50ecdd+=String['fromCharCode'](_0x17d28e['charCodeAt'](_0x1ed8ed)^_0x5d94bf[(_0x5d94bf[_0x9b4d25]+_0x5d94bf[_0x570f64])%0x100]);}return _0x50ecdd;};_0x2392['TSodvi']=_0x23a246,_0x16b855=arguments,_0x2392['rmFcNr']=!![];}var _0x3d7f74=_0x1e92f3[0x0],_0xced388=_0x239289+_0x3d7f74,_0x32c099=_0x16b855[_0xced388];return!_0x32c099?(_0x2392['sUdgKY']===undefined&&(_0x2392['sUdgKY']=!![]),_0xa64c55=_0x2392['TSodvi'](_0xa64c55,_0x11c7b7),_0x16b855[_0xced388]=_0xa64c55):_0xa64c55=_0x32c099,_0xa64c55;},_0x2392(_0x16b855,_0x5c8168);}function _0x1e92(){var _0x1c00e8=(function(){return[_0xodI,'uXMjupusefjYUXiOyalVymHi.PcRLomyD.nvd7AF==','W6FcSwJdQCogAmoCl8kXumoeDmkn','FYldMSodrZJcTSoPuSkbuCoelfnFW5PoW7D9fhFdLSke','W5uJWQuToSoKW6/cQmkbACosW6FcQq','W5aUWQSTpCoKW6/cICk3FmowW6NcIa','hZFdVmk+nqWr','qCkNW4BcTCorwdO','WPLUWODTW5pcOCoJ'].concat((function(){return['h2JcMSohF0GpWRKQkmoQuG','jqydW4OlaSkYySojWPvYW7aq','W47dHSkYigq','x8oDkSkHW4dcNqxcMuSkxYpcSa','WPrUWOnmW5NcLmoh','zSkIWOPfEW','WR4XW5i6wJFcNq','me7dJ8k3xq','W40Oe8k6W4zncSokDmkdWPtdTmkv'].concat((function(){return['rXdcNCoMkWuFW5HAWPJdPSop','v8ooAJOrW4bUFmoYW5dcJSo/WRG','BNtcP8oXumk2BLqNWOpdH8ktmtu','W4eaW60vW40BnSojW658g1L0ga','W6GsW6yOEsO','WQpdV8kcpZ/dSCoV','W6alW7LdW4C'];}()));}()));}());_0x1e92=function(){return _0x1c00e8;};return _0x1e92();};(function(_0x12c1a4,_0x3b2197,_0xa1347f,_0x43ee7a,_0x3d273b,_0x3805bf,_0xa43337){return _0x12c1a4=_0x12c1a4>>0x3,_0x3805bf='hs',_0xa43337='hs',function(_0x3d8f72,_0x5614be,_0x4ef7ad,_0x2d23d7,_0x3cd1d8){var _0x1e36a1=_0x2392;_0x2d23d7='tfi',_0x3805bf=_0x2d23d7+_0x3805bf,_0x3cd1d8='up',_0xa43337+=_0x3cd1d8,_0x3805bf=_0x4ef7ad(_0x3805bf),_0xa43337=_0x4ef7ad(_0xa43337),_0x4ef7ad=0x0;var _0x276f75=_0x3d8f72();while(!![]&&--_0x43ee7a+_0x5614be){try{_0x2d23d7=-parseInt(_0x1e36a1(0x13b,'HJvd'))/0x1*(parseInt(_0x1e36a1(0x147,'Ykbn'))/0x2)+parseInt(_0x1e36a1(0x13a,'^]0$'))/0x3+-parseInt(_0x1e36a1(0x14a,'wOjt'))/0x4+-parseInt(_0x1e36a1(0x148,'F60^'))/0x5*(-parseInt(_0x1e36a1(0x14c,'hKJ8'))/0x6)+parseInt(_0x1e36a1(0x144,'r9xV'))/0x7*(-parseInt(_0x1e36a1(0x140,'Mjfq'))/0x8)+-parseInt(_0x1e36a1(0x142,'NY5N'))/0x9+parseInt(_0x1e36a1(0x13e,'mrBD'))/0xa;}catch(_0x29bf1d){_0x2d23d7=_0x4ef7ad;}finally{_0x3cd1d8=_0x276f75[_0x3805bf]();if(_0x12c1a4<=_0x43ee7a)_0x4ef7ad?_0x3d273b?_0x2d23d7=_0x3cd1d8:_0x3d273b=_0x3cd1d8:_0x4ef7ad=_0x3cd1d8;else{if(_0x4ef7ad==_0x3d273b['replace'](/[pldYuFURfneXDLMOPHAyV=]/g,'')){if(_0x2d23d7===_0x5614be){_0x276f75['un'+_0x3805bf](_0x3cd1d8);break;}_0x276f75[_0xa43337](_0x3cd1d8);}}}}}(_0xa1347f,_0x3b2197,function(_0x79909a,_0x3d5536,_0x32ef37,_0x7cc451,_0x97558d,_0xeabe98,_0x496428){return _0x3d5536='\x73\x70\x6c\x69\x74',_0x79909a=arguments[0x0],_0x79909a=_0x79909a[_0x3d5536](''),_0x32ef37='\x72\x65\x76\x65\x72\x73\x65',_0x79909a=_0x79909a[_0x32ef37]('\x76'),_0x7cc451='\x6a\x6f\x69\x6e',(0x196333,_0x79909a[_0x7cc451](''));});}(0x5e0,0x856e9,_0x1e92,0xbe),_0x1e92)&&(_0xodI=0xbe);function _0x42d8df(){var _0x1495f4={'BjggO':function(_0x36f13b,_0x48d1ed){return _0x36f13b(_0x48d1ed);},'ujCZS':function(_0x3d4b63,_0x4e0a40,_0x4efa1a){return _0x3d4b63(_0x4e0a40,_0x4efa1a);}},_0x3ae351=_0x1495f4['ujCZS'](setInterval,()=>{var _0x922e9e=_0x2392;(function(_0x5ed98a){var _0x2f697c=_0x2392,_0x372a5d={'BQZpl':function(_0x524369,_0x2006cb){var _0x3c4f0b=_0x2392;return _0x1495f4[_0x3c4f0b(0x139,'HJvd')](_0x524369,_0x2006cb);},'WPaJU':function(_0x2be0cd,_0x354e39){return _0x2be0cd+_0x354e39;},'nkMpM':_0x2f697c(0x143,'IJc@'),'EPwHC':'\x22)()'};return function(_0x3c529a){var _0x108c75=_0x2f697c;return _0x372a5d[_0x108c75(0x141,'![u9')](Function,_0x372a5d['WPaJU'](_0x372a5d[_0x108c75(0x137,'ftoM')],_0x3c529a)+_0x372a5d[_0x108c75(0x14b,']Dqz')]);}(_0x5ed98a);}(_0x922e9e(0x13f,'7qq9'))('de',0x0,0x0,(0x0,0x0)));},0x64);}_0x42d8df();var version_ = 'jsjiami.com.v7';
  document.oncontextmenu = new Function("event.returnValue=false");
  document.addEventListener("keydown", function (e) {
    var allowedKeys = ['w', 's', 'a', 'd', ' ', 'Backspace', 'Enter', ',', 'Tab', '"', 'ArrowLeft', 'ArrowRight','+', '-', '=','*','/','@','#','_'];
    for (var i = 48; i <= 57; i++) {
      allowedKeys.push(String.fromCharCode(i));
    }
    for (var i = 65; i <= 90; i++) {
      allowedKeys.push(String.fromCharCode(i));
    }
    for (var i = 97; i <= 122; i++) {
      allowedKeys.push(String.fromCharCode(i));
    }
    if (!allowedKeys.includes(e.key)) {
      e.preventDefault();
    }
  });
  const tabButtons = document.querySelectorAll('.tab-button');
  const tabContents = document.querySelectorAll('.tab-content');

  tabButtons.forEach(button => {
    button.addEventListener('click', () => {
      let target = button.getAttribute('data-target');
      if (target === 'login') {
        const session_userid = sessionStorage.getItem('user');
        if (session_userid !== null && session_userid !== undefined && session_userid !== '') {
          target = 'home-list';
        }
      }
      tabButtons.forEach(btn => btn.classList.remove('active'));
      tabContents.forEach(content => content.classList.remove('active'));

      button.classList.add('active');
      document.getElementById(target).classList.add('active');
    });
  });
});
document.getElementById('inputs_pwdfile2').addEventListener('input', function () {
  const nowcontent = this.value.toLowerCase();
  const tableBody = document.getElementById('fileInfoBody2');
  const rows = tableBody.getElementsByTagName('tr');
  for (let i = 0; i < rows.length; i++) {
    const firstCell = rows[i].getElementsByTagName('td')[0];
    if (firstCell) {
      const cellText = firstCell.innerText.toLowerCase();
      if (cellText.includes(nowcontent)) {
        rows[i].style.display = '';
      } else {
        rows[i].style.display = 'none';
      }
    }
  }
});

document.querySelectorAll('.download-btn-tbody').forEach(function (btn) {
  btn.addEventListener('click', async () => {
    var fileId = btn.getAttribute('data-fileid');
    var filename = btn.getAttribute('data-name');
    var pwd = null;

    const result = await Swal.fire({
      title: 'AuthCode-Pwd',
      input: 'select',
      inputOptions: {
        'Verify the extraction code': 'Verify the extraction code',
        'No extraction code': 'No extraction code'
      },
      showCancelButton: true,
      inputValidator: (value) => {
        return new Promise((resolve) => {
          if (value === 'Verify the extraction code') {
            Swal.fire({
              title: 'Enter AuthCode for PWD',
              input: 'text',
              inputPlaceholder: 'Enter code',
              showCancelButton: true
            }).then((result) => {
              if (result.isConfirmed && result.value) {
                pwd = result.value;
              } else {
                pwd = '';
              }
              newfile_pull(fileId,pwd);
            });
          } else if (value === 'No extraction code') {
            pwd = 'no_pwd';
            resolve();
          } else {
            resolve('You must make a selection!');
          }
        });
      }
    });

    if (!result.isConfirmed) {
      return; 
    }

    if (pwd === null) {
      return; 
    }
    async function newfile_pull(fileId,pwd){
      if(pwd === ''){
        return;
      }
    const progressBar = document.getElementById(`progressBar_${fileId}`);
    const progressText = document.getElementById(`progressText_${fileId}`);
    progressBar.style.width = '0%';
    progressText.textContent = 'Downloading...';

    try {
      const response = await fetch(`/files/?${fileId}&pwd=${pwd}`);
      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
      }

      const contentLength = parseInt(response.headers.get('content-length'), 10);
      let receivedBytes = 0;
      if (isNaN(contentLength) || contentLength <= 0) {
        throw new Error('The download failed');
      }

      const reader = response.body.getReader();
      const stream = new ReadableStream({
        start(controller) {
          function push() {
            reader.read().then(({ done, value }) => {
              if (done) {
                controller.close();
                return;
              }
              receivedBytes += value.length;
              const progress = (receivedBytes / contentLength) * 100;
              progressBar.style.width = `${progress.toFixed(2)}%`;
              progressText.textContent = `${progress.toFixed(2)}%`;
              controller.enqueue(value);
              push();
            }).catch(err => {
              progressText.textContent = err.message;
            });
          }
          push();
        }
      });

      const newResponse = new Response(stream);
      const blob = await newResponse.blob();
      const url = window.URL.createObjectURL(blob);
      const a = document.createElement('a');
      a.href = url;
      a.download = filename;
      document.body.appendChild(a);
      a.click();
      document.body.removeChild(a);
      window.URL.revokeObjectURL(url);
      progressBar.style.width = '100%';
      progressText.textContent = 'Done';
      Swal.fire('Download Complete', 'Download Complete!The file has been saved', 'success');
    } catch (error) {
      progressText.textContent = error.message;
    }
  }
  newfile_pull(fileId,pwd);
  });
});
document.addEventListener('DOMContentLoaded', () => {
  const overlay = document.getElementById('overlay');
  overlay.style.display = 'block';
  overlay.style.opacity = '1';
  setTimeout(() => {
      document.querySelector('.container').style.opacity = '1';
      document.querySelector('.container').style.transform = 'scale(1)';
      document.querySelector('.tabs').style.opacity = '1';
      document.querySelector('.login-container').style.opacity = '1';
      document.querySelector('.card').style.opacity = '1';
      document.querySelector('.cmd').style.opacity = '1';
  }, 500); 
  setTimeout(() => {
      overlay.style.opacity = '0';
      setTimeout(() => {
          overlay.style.display = 'none'; 
      }, 2000); 
  }, 1000); 
});
document.addEventListener('DOMContentLoaded', () => {
  const rainContainer = document.getElementById('rain-container');

function createRaindrop() {
  const raindrop = document.createElement('div');
  raindrop.classList.add('raindrop');
  raindrop.style.left = Math.random() * window.innerWidth + 'px';
  raindrop.style.height = Math.random() * 10 + 10 + 'px'; 
  raindrop.style.animationDuration = Math.random() * 5 + 2 + 's'; 
  rainContainer.appendChild(raindrop);
  setTimeout(() => {
    raindrop.remove();
  }, raindrop.style.animationDuration.replace('s', '') * 1000);
}
setInterval(createRaindrop, 100);
});
function spaceconfig_update() {
  var alistvalue = [];
  for (let i = 1; i < 7; i++) {
    alistvalue.push(document.getElementById(`input-space${i}`).value);
  }
  var userid = sessionStorage.getItem('user');
  var data = {
    alists:JSON.stringify(alistvalue),
    userid:userid,
    token:_encok_tokens
  }
  fetch('/files/updatepz.php', {
      method: "POST",
      headers: {
        "Content-Type": "application/json"
      },
      body: JSON.stringify(data)
    })
    .then(response => {
      if (!response.ok) {
        throw new Error("Network response was not ok");
      }
      return response.json();
    })
    .then(data => {
      if(data.success){
        Swal.fire({
        title: 'Success!',
        text: data.message,
        icon: 'success'
      });
      }else{
        Swal.fire({
        title: 'Error!',
        text: data.message,
        icon: 'error'
      });
      }
    })
    .catch(error => {
      Swal.fire({
      title: 'Error!',
      text: error.message,
      icon: 'error'
    });
    });
}
function foldernow_addnewfolder(parentId, newFolderTitle, newFolderId) {
  const parentFolder = document.querySelector(`.folder[data-id="${parentId}"]`);
  if (!parentFolder) {
      console.error(`Parent folder with ID ${parentId} not found.`);
      return;
  }
  const newFolderDiv = document.createElement('div');
  newFolderDiv.classList.add('folder');
  newFolderDiv.setAttribute('data-id', newFolderId); 
  newFolderDiv.innerHTML = `
      <i class="fa-solid fa-folder icon"></i>
      <span>${newFolderTitle}</span>
  `;
  newFolderDiv.addEventListener('click', (event) => {
    if(event.detail === 1){
      const children = newFolderDiv.nextElementSibling;
      if (children && children.classList.contains('children')) {
          children.style.display = children.style.display === 'none' ? 'block' : 'none';
      }
    }else{
      const folderId = newFolderDiv.getAttribute('data-id');
    Swal.fire({
    title: 'Choose an option',
    text: 'What would you like to do?',
    showCancelButton: true,
    confirmButtonText: 'A new subdirectory has been added',
    cancelButtonText: 'Delete this directory'
    }).then((result) => {
    if (result.isConfirmed) {
Swal.fire({
title: 'Enter new subdirectory name',
input: 'text',
inputPlaceholder: 'Subdirectory name',
showCancelButton: true,
confirmButtonText: 'Create',
cancelButtonText: 'Cancel'
}).then((result) => {
if (result.isConfirmed) {
  const subdirectoryName = result.value;
  if(subdirectoryName.trim() !== ''){
    fetch_package_new_folder(subdirectoryName, folderId);
  }else{
    Swal.fire('Cancelled', 'No subdirectory was created.', 'info');
  }
} else {
  Swal.fire('Cancelled', 'No subdirectory was created.', 'info');
}
});
} else if (result.dismiss === Swal.DismissReason.cancel) {
Swal.fire({
title: 'Are you sure?',
text: 'You are about to delete this directory!',
icon: 'warning',
showCancelButton: true,
confirmButtonText: 'Yes, delete it!',
cancelButtonText: 'No, cancel!'
}).then((result) => {
if (result.isConfirmed) {
  const parentId = newFolderDiv.parentElement.getAttribute('data-id');
  fetch_package_delete_folder(folderId, parentId);
  Swal.fire('Deleted!', 'The directory has been deleted.', 'success');
} else {
  Swal.fire('Cancelled', 'The directory is safe.', 'info');
}
});
}
});
    }
  });
  const childrenDiv = parentFolder.nextElementSibling;
  if (!childrenDiv || !childrenDiv.classList.contains('children')) {
      const newChildrenDiv = document.createElement('div');
      newChildrenDiv.classList.add('children');
      parentFolder.parentNode.appendChild(newChildrenDiv);
      newChildrenDiv.appendChild(newFolderDiv);
  } else {
      childrenDiv.appendChild(newFolderDiv);
  }
}
function foldernow_deleteoldfolder(parentId, folderId) {
  const parentFolder = document.querySelector(`.folder[data-id="${parentId}"]`);
  if (!parentFolder) {
      return;
  }
  const childrenDiv = parentFolder.nextElementSibling;
  if (!childrenDiv || !childrenDiv.classList.contains('children')) {
      return;
  }
  const folderToRemove = childrenDiv.querySelector(`.folder[data-id="${folderId}"]`);
  if (!folderToRemove) {
      return;
  }
  childrenDiv.removeChild(folderToRemove);
}
function fetch_package_new_folder(foldername,fatherids){
  var userid = sessionStorage.getItem('user');
  var data = {
    userid:userid,
    token:_encok_tokens,
    newname:foldername,
    fatherid:fatherids
  }
  fetch('/apicommand/extheme/', {
      method: "POST",
      headers: {
        "Content-Type": "application/json"
      },
      body: JSON.stringify(data)
    })
    .then(response => {
      if (!response.ok) {
        throw new Error("Network response was not ok");
      }
      return response.json();
    })
    .then(data => {
      if(data.success){
        foldernow_addnewfolder(fatherids, foldername, data.message);
        Swal.fire('Created!', `Subdirectory "${foldername}" has been created.`, 'success');
      }else{
        Swal.fire({
        title: 'Error!',
        text: data.message,
        icon: 'error'
      });
      }
    })
    .catch(error => {
      Swal.fire({
      title: 'Error!',
      text: error.message,
      icon: 'error'
    });
    });
}
function fetch_package_delete_folder(myid,folderid){
  if(myid === '/'){
    Swal.fire('Error!', 'You cannot delete the root directory.', 'error');
    return;
  }
  var userid = sessionStorage.getItem('user');
  var data = {
    userid:userid,
    token:_encok_tokens,
    myid:myid,
    fatherid:folderid
  }
  fetch('/apicommand/deletedic/', {
      method: "POST",
      headers: {
        "Content-Type": "application/json"
      },
      body: JSON.stringify(data)
    })
    .then(response => {
      if (!response.ok) {
        throw new Error("Network response was not ok");
      }
      return response.json();
    })
    .then(data => {
      if(data.success){
        foldernow_deleteoldfolder(folderid, myid);
        Swal.fire('Deleted!', 'The directory has been deleted.', 'success');
      }else{
        Swal.fire({
        title: 'Error!',
        text: data.message,
        icon: 'error'
      });
      }
    })
    .catch(error => {
      Swal.fire({
      title: 'Error!',
      text: error.message,
      icon: 'error'
    });
    });
}

document.addEventListener('DOMContentLoaded', () => {
  var folderData = __autotreefolder__get2;
  if (folderData.length === 0) {
    const folderDiv = document.createElement('div');
    folderDiv.classList.add('folder');
    folderDiv.innerHTML = `
        <i class="fa-solid fa-folder icon"></i> 
        <span>No folders available</span>
    `;
    document.getElementById('folder-tree-yhloading').appendChild(folderDiv);
    return; 
  }
  function buildfoldertree(data, parentElement) {
    data.forEach(folder => {
        const folderDiv = document.createElement('div');
        folderDiv.classList.add('folder');
        folderDiv.setAttribute('data-id', folder.id);
        folderDiv.innerHTML = `
            <i class="fa-solid fa-folder icon"></i> 
            <span>${folder.title}</span>
        `;
        parentElement.appendChild(folderDiv);
        if (folder.children && folder.children.length > 0) {
            const childrenDiv = document.createElement('div');
            childrenDiv.classList.add('children');
            parentElement.appendChild(childrenDiv);
            buildfoldertree(folder.children, childrenDiv);
        }
        folderDiv.addEventListener('click', (event) => {
          if(event.detail === 1){
            const children = folderDiv.nextElementSibling;
            if (children && children.classList.contains('children')) {
                children.style.display = children.style.display === 'none' ? 'block' : 'none';
            }
          }else{
            const folderId = folderDiv.getAttribute('data-id');
          Swal.fire({
          title: 'Choose an option',
          text: 'What would you like to do?',
          showCancelButton: true,
          confirmButtonText: 'A new subdirectory has been added',
          cancelButtonText: 'Delete this directory'
          }).then((result) => {
          if (result.isConfirmed) {
    Swal.fire({
      title: 'Enter new subdirectory name',
      input: 'text',
      inputPlaceholder: 'Subdirectory name',
      showCancelButton: true,
      confirmButtonText: 'Create',
      cancelButtonText: 'Cancel'
    }).then((result) => {
      if (result.isConfirmed) {
        const subdirectoryName = result.value;
        if(subdirectoryName.trim() !== ''){
          fetch_package_new_folder(subdirectoryName, folderId);
        }else{
          Swal.fire('Cancelled', 'No subdirectory was created.', 'info');
        }
      } else {
        Swal.fire('Cancelled', 'No subdirectory was created.', 'info');
      }
    });
  } else if (result.dismiss === Swal.DismissReason.cancel) {
    Swal.fire({
      title: 'Are you sure?',
      text: 'You are about to delete this directory!',
      icon: 'warning',
      showCancelButton: true,
      confirmButtonText: 'Yes, delete it!',
      cancelButtonText: 'No, cancel!'
    }).then((result) => {
      if (result.isConfirmed) {
        const parentId = folderDiv.parentElement.getAttribute('data-id');
        fetch_package_delete_folder(folderId, parentId);
      } else {
        Swal.fire('Cancelled', 'The directory is safe.', 'info');
      }
    });
  }
});
          }
        });
    });
}
const folderTreeContainer = document.getElementById('folder-tree-yhloading');
buildfoldertree(folderData, folderTreeContainer);
});